<template>
  <div class="listing-container">
    <!-- 顶部标题 -->
    <div class="page-header">
      <div class="header-title">创建记录</div>
    </div>

    <!-- 商品信息 -->
    <div class="section">
      <div class="section-badge">商品信息</div>
      <div class="product-card">
        <div class="product-name">{{ outbound["689ad8a3f23d51578296dfbc"] }}</div>
        <div class="product-meta">
          <div class="meta-row">
            <span class="meta-label">供应商</span>
            <span class="meta-value">{{ outbound["689aedb9f23d51578296e82a"] }}</span>
          </div>
          <div class="meta-row">
            <span class="meta-label">保质期单位</span>
            <span class="meta-value">{{outbound["689ad90af23d51578296e024"]}}</span>
          </div>
          <div class="meta-row">
            <span class="meta-label">保质期</span>
            <span class="meta-value">{{  outbound["689ad90af23d51578296e023"] }}</span>
          </div>
          <div class="meta-row">
            <span class="meta-label">SKUID</span>
            <span class="meta-value">{{ outbound["687859e0a462f1cb468b32c8"] }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stat-row">
      <span class="stat-label">剩余入库数</span>
      <span class="stat-number">{{(  RemainingQuantity > 0) ? RemainingQuantity  : 0}}</span>
    </div>

    <!-- 表单区域 -->
    <div class="form">
      <div class="field required clickable" @click="showDatePicker = true">
        <div class="field-label">商品生产日期</div>
        <div class="field-control" :class="{ placeholder: !formData.productionDate }">
          {{ formData.productionDate || '请选择日期' }}
          <span class="arrow">›</span>
        </div>
      </div>

      <div class="field required" :class="{ 'error': showGoodError }">
        <div class="field-label">良品到货数</div>
        <input 
          class="input" 
          v-model="formData.goodQuantity"
          type="number" 
          min="0"
          placeholder="请填写数值" 
          @input="validateGoodQuantity"
        />
        <div v-if="showGoodError" class="error-message">请填写良品到货数</div>
      </div>

      <div class="field" :class="{ 'error': showDefectiveError }">
        <div class="field-label">残品到货数</div>
        <input 
          class="input" 
          v-model="formData.defectiveQuantity"
          type="number" 
          min="0"
          placeholder="0" 
          @input="validateDefectiveQuantity"
        />
        <div v-if="showDefectiveError" class="error-message">请填写残品到货数</div>
      </div>
    </div>

    <!-- Vant 日历选择器（移动端更稳） -->
    <van-calendar
      v-model:show="showDatePicker"
      type="single"
      title="选择生产日期"
      :min-date="minDate"
      :max-date="maxDate"
      color="#1989fa"
      @confirm="onCalendarConfirm"
    />

    <!-- 底部操作区 -->
    <div class="footer">
      <button class="btn ghost" @click="showConfirmDialog('continue')">提交并继续创建</button>
      <button class="btn primary" :disabled="submitting || submitted" @click="showConfirmDialog('submit')">{{ submitted ? '已提交' : (submitting ? '提交中…' : '提交') }}</button>
    </div>

    <!-- 确认对话框 -->
    <van-dialog
      v-model:show="showConfirm"
      title="确认提交"
      :message="confirmMessage"
      show-cancel-button
      confirm-button-text="确认"
      cancel-button-text="取消"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();

const props = defineProps({
  planId: { type: String, default: '' },
  outbound: { type: Object, default: null }
});

const RemainingQuantity = ref()

onMounted(() => {
  console.log('props.outbound:', props.outbound);

  RemainingQuantity.value = props.outbound['689d7dd9c82bfc2f84b3961c']
  
  try {
    formData.value.rowId = props.outbound?.rowid || '';
  } catch (e) {}
  const today = new Date();
  formData.value.productionDate = formatDate(today);
});

const submitting = ref(false);
const submitted = ref(false);

const submit = async (submitType = 'submit') => {
  if (submitting.value || submitted.value) return;

  // 校验：良品必填，且两项均不得为负
  const good = formData.value.goodQuantity;
  const defective = formData.value.defectiveQuantity;
  if (good === '' || isNaN(Number(good))) return;
  if (Number(good) < 0 || Number(defective || 0) < 0) return;

  submitting.value = true;
  try {
    const payload = { ...formData.value };
    if (payload.goodQuantity !== '') payload.goodQuantity = Number(payload.goodQuantity);
    if (payload.defectiveQuantity !== '') payload.defectiveQuantity = Number(payload.defectiveQuantity);

    const url = 'https://www.dachen.vip/api/workflow/hooks/Njg5OWNhOGZmNWUwOTQ2ZjljMzg4ZGE1';
    const res = await axios.post(url, payload, {
      headers: { 'Content-Type': 'application/json' }
    });
    const result = res?.data ?? {};
    console.log('[Submit] response:', result);

    if (result?.status === 1) {
      // 更新剩余入库数量
      const totalQuantity = Number(payload.goodQuantity) + Number(payload.defectiveQuantity);
      RemainingQuantity.value = Math.max(0, RemainingQuantity.value - totalQuantity);
      submitted.value = true;
      
      if (submitType === 'submit') {
        // 普通提交：回退到上一个页面
        setTimeout(() => {
          router.back();
        }, 1000);
      } else if (submitType === 'continue') {
        // 提交并继续创建：重置表单，继续停留在当前页面
        setTimeout(() => {
          // 重置表单数据
          formData.value.goodQuantity = '';
          formData.value.defectiveQuantity = '0';
          formData.value.productionDate = formatDate(new Date());
          // 重置提交状态
          submitted.value = false;
          // 显示成功提示
          if (window.van && window.van.showToast) {
            window.van.showToast({
              message: '提交成功，已重置表单',
              type: 'success',
              duration: 2000
            });
          }
        }, 1000);
      }
    }
  } catch (err) {
    console.error('[Submit] request failed:', err);
  } finally {
    submitting.value = false;
  }
};

const getTimeUnit = (time) => {
  console.log('time:', time);
  if (time == 'a164d0b2-85d2-4a72-aa5c-cddd1c133886') {
    return '天'
  } else if (time == '689d48fe-fce4-4fe8-8412-360125be5fd2') {
    return '月'
  } else if (time == 'b8ca6aef-1e29-4d1d-9c72-4ce802b9731c') {
    return '年'
  }
  else{
    return '无保质期'
  }
}

// 表单数据
const formData = ref({
  productionDate: '',
  goodQuantity: '',
  defectiveQuantity: '0',
  rowId: ''
});

// 日期选择器显示状态
const showDatePicker = ref(false);

// 确认对话框相关
const showConfirm = ref(false);
const confirmType = ref('');
const confirmMessage = ref('');

// 验证错误状态
const showGoodError = ref(false);
const showDefectiveError = ref(false);

// 日期选择器相关
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2030, 11, 31);

// 日历确认事件
const onCalendarConfirm = (date) => {
  if (Array.isArray(date)) {
    date = date[0];
  }
  formData.value.productionDate = formatDate(date);
  showDatePicker.value = false;
};

// 显示确认对话框
const showConfirmDialog = (type) => {
  confirmType.value = type;
  if (type === 'continue') {
    confirmMessage.value = '确认提交并继续创建记录吗？';
  } else {
    confirmMessage.value = '确认提交记录吗？';
  }
  showConfirm.value = true;
};

// 处理确认提交
const handleConfirm = () => {
  // 先进行表单验证
  if (!validateForm()) {
    return;
  }
  
  // 根据确认类型调用不同的提交方式
  submit(confirmType.value);
};

// 验证良品到货数
const validateGoodQuantity = () => {
  const value = formData.value.goodQuantity;
  if (value === '' || isNaN(Number(value))) {
    showGoodError.value = true;
  } else {
    showGoodError.value = false;
  }
};

// 验证残品到货数
const validateDefectiveQuantity = () => {
  const value = formData.value.defectiveQuantity;
  if (value === '' || isNaN(Number(value))) {
    showDefectiveError.value = true;
  } else {
    showDefectiveError.value = false;
  }
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 验证良品到货数
  if (formData.value.goodQuantity === '' || isNaN(Number(formData.value.goodQuantity))) {
    showGoodError.value = true;
    isValid = false;
  }
  
  // 验证残品到货数
  if (formData.value.defectiveQuantity === '' || isNaN(Number(formData.value.defectiveQuantity))) {
    showDefectiveError.value = true;
    isValid = false;
  }
  
  // 如果验证失败，显示Toast提示
  if (!isValid) {
    // 使用Vant的Toast组件
    if (window.van && window.van.showToast) {
      window.van.showToast({
        message: '请完善必填信息',
        type: 'fail',
        duration: 2000
      });
    }
  }
  
  return isValid;
};

function formatDate(d) {
  const y = d.getFullYear();
  const m = `${d.getMonth() + 1}`.padStart(2, '0');
  const day = `${d.getDate()}`.padStart(2, '0');
  return `${y}-${m}-${day}`;
}

// 监听表单数据变化
const handleFormChange = () => {
  console.log('表单数据变化:', formData.value);
};
</script>

<style scoped>
/* 页面背景与结构 */
.listing-container {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 16px 16px 96px; /* 预留底部按钮空间 */
  color: #222;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部标题 */
.page-header {
  background: #fff;
  border-radius: 16px;
  padding: 16px 18px;
  margin-bottom: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
}
.header-title {
  font-size: 18px;
  font-weight: 700;
}

/* 页面内状态提示 */
.status-banner {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0 0;
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid transparent;
}
.status-banner .status-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  font-weight: 700;
  font-size: 12px;
}
.status-banner.info {
  background: #eff6ff;
  color: #1e3a8a;
  border-color: #bfdbfe;
}
.status-banner.info .status-icon {
  background: #3b82f6;
  color: #fff;
}
.status-banner.success {
  background: #ecfdf5;
  color: #065f46;
  border-color: #a7f3d0;
}
.status-banner.success .status-icon {
  background: #10b981;
  color: #fff;
}
.status-banner.error {
  background: #fef2f2;
  color: #991b1b;
  border-color: #fecaca;
}
.status-banner.error .status-icon {
  background: #ef4444;
  color: #fff;
}

/* 区块与卡片 */
.section { margin-top: 8px; }
.section-badge {
  display: inline-block;
  background: rgba(248, 179, 0, 0.1);
  color: #000000;
  border-radius: 12px;
  padding: 6px 12px;
  font-size: 13px;
  margin-bottom: 10px;
}

.product-card {
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  border: 1px solid rgba(0, 0, 0, 0.06);
}
.product-name {
  font-size: 18px;
  font-weight: 800;
  color: #000000;
  margin-bottom: 12px;
}
.product-meta { display: flex; flex-direction: column; gap: 8px; }
.meta-row { display: flex; align-items: center; gap: 12px; }
.meta-label { width: 90px; font-size: 14px; color: #000000; }
.meta-value { font-size: 14px; color: #000000; font-weight: 600; }

/* 统计信息 */
.stat-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 14px;
  padding: 14px 16px;
  margin-top: 14px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.06);
  border: 1px solid rgba(0, 0, 0, 0.06);
}
.stat-label { color: #000000; font-size: 14px; }
.stat-number { color: #000000; font-size: 18px; font-weight: 800; }

/* 表单区域 */
.form { margin-top: 14px; display: flex; flex-direction: column; gap: 12px; }
.field {
  background: #fff;
  border-radius: 14px;
  padding: 12px 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid rgba(0, 0, 0, 0.06);
  box-shadow: 0 2px 12px rgba(0,0,0,0.04);
}
.field.required .field-label::before {
  content: '*';
  color: #ef4444;
  margin-right: 6px;
}
.field-label { color: #000000; font-size: 14px; font-weight: 600; }
.field-control { color: #000000; font-size: 14px; font-weight: 500; }
.field-control.placeholder { color: #000000; display: flex; align-items: center; gap: 6px; }
.clickable .arrow { color: #000000; font-size: 18px; line-height: 1; }

.input {
  flex: 1;
  margin-left: 10px;
  height: 34px;
  border: none;
  outline: none;
  background: transparent;
  text-align: right;
  font-size: 14px;
  color: #000000;
}
.input::placeholder { color: #000000; }

/* 错误状态样式 */
.field.error {
  border-color: #ef4444;
  background: #fef2f2;
}

.error-message {
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
  font-weight: 500;
}

/* 底部操作区 */
.footer {
  position: fixed;
  left: 0; right: 0; bottom: 0;
  display: flex;
  gap: 12px;
  padding: 12px 16px calc(env(safe-area-inset-bottom, 0) + 12px);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(6px);
  box-shadow: 0 -6px 20px rgba(0,0,0,0.08);
}
.btn {
  flex: 1;
  height: 44px;
  border-radius: 22px;
  border: none;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: 1px;
}
.btn.ghost {
  background: rgba(248, 179, 0, 0.1);
  color: #000000;
}
.btn.primary {
  background: #f8b300;
  color: #000000;
}
.btn.primary:disabled {
  opacity: 0.6;
}

/* Vant 样式覆盖 */
:deep(.van-popup) {
  border-radius: 16px 16px 0 0;
}

:deep(.van-datetime-picker) {
  height: 100%;
}

:deep(.van-picker__toolbar) {
  background: #f8fafc;
}

:deep(.van-picker__title) {
  font-weight: 600;
  color: #000000;
}

:deep(.van-picker__confirm) {
  color: #f8b300;
  font-weight: 600;
}

:deep(.van-picker__cancel) {
  color: #000000;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .product-name { font-size: 16px; }
  .stat-number { font-size: 16px; }
  
  .date-picker {
    margin: 20px;
    min-width: auto;
    width: calc(100% - 40px);
  }
}
</style>
